﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;


namespace LectorHuellaC
{
    public partial class AltaUsuario : Form, DPFP.Capture.EventHandler 
    {
        String versionapp = "A 1.0";

        public AltaUsuario()
        {
            InitializeComponent();
            this.Text = ":: Reloj Checador :: " + versionapp + " (" + this.Text + ")";
        }
        String Id_empleado;
        //public AltaUsuario(String id_user)
        //{
         //7   Id_usuarios=id_user;
        //}

 
        public DPFP.Sample ImagenSample;
        public DPFP.Sample ImagenSampleValidar;
        public DPFP.Template ImagenTemplate;
        public DPFP.Template Template;
        public DPFP.Verification.Verification Verificator;
        private DPFP.Processing.Enrollment Enroller;
        private DPFP.Capture.Capture Capturer;
        string IdEmpleado;

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            //string IdEmpresa = Settings1.Default.IdEmpresa.ToString();
            //string consulta = "Select Nombre from usuarios where IdEmpresa = " + IdEmpresa + " And IdEmpleado = '" + txtNumero.Text + "' "; 
            //ConectaBD clsConBD = new ConectaBD();
            //DataSet resultado = clsConBD.Consulta(consulta);
            //txtNombre.Text = resultado.Tables[0].Rows[0]["Nombre"].ToString();
        }


        #region EventosLector

        protected virtual void Init()
        {
            Enroller = new DPFP.Processing.Enrollment();			// Create an enrollment.
            
            try
            {
                Capturer = new DPFP.Capture.Capture();				// Create a capture operation.

                if (null != Capturer)
                {
                    //SetPrompt("Dispositivo inicializado.");
                    Capturer.EventHandler = this;					// Subscribe for capturing events.
                }
                else
                {
                    //SetPrompt("No se puede iniciar la operacion de captura");
                }
            }
            catch
            {
                MessageBox.Show("No se puede iniciar la operacion de captura", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        protected virtual void Process(DPFP.Sample Sample)
        {
            ImagenSample = Sample;
            // Draw fingerprint sample image.
            DrawPicture(ConvertSampleToBitmap(Sample));


            //************** ENROLLMENT ************************************

            // Process the sample and create a feature set for the enrollment purpose.
            DPFP.FeatureSet features = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Enrollment);

            // Check quality of the sample and add to enroller if it's good
            if (features != null) 
                try
                {
                    while (Enroller.TemplateStatus != DPFP.Processing.Enrollment.Status.Ready)
                    {
                        //MakeReport("The fingerprint feature set was created.");
                        Enroller.AddFeatures(features);		// Add feature set to template.
                    }
                }
                finally
                {
                    OnTemplate(null); // Establece a Null el Template
                    //UpdateStatus();

                     //Check if template has been created.
                    switch (Enroller.TemplateStatus)
                    {
                        case DPFP.Processing.Enrollment.Status.Ready:	// report success and stop capturing                            
                            OnTemplate(Enroller.Template); //Asigna Template 
                            //SetPrompt("Click Close, and then click Fingerprint Verification.");
                            break;

                        case DPFP.Processing.Enrollment.Status.Failed:	// report failure and restart capturing
                            Enroller.Clear();
                            Stop();
                            OnTemplate(null);
                            Start();
                            break;
                    }

                }
            //************** ENROLLMENT ************************************

        }


        protected void Start()
        {
            if (null != Capturer)
            {
                try
                {
                    Capturer.StartCapture();
                    //SetPrompt("Using the fingerprint reader, scan your fingerprint.");
                    //SetPrompt("Lector de huella listo para capturar ... ");
                }
                catch
                {
                    //SetPrompt("Can't initiate capture!");
                    //SetPrompt("No se puede iniciar la captura");
                }
            }
        }


        protected void Stop()
        {
            if (null != Capturer)
            {
                try
                {
                    Capturer.StopCapture();
                    //SetPrompt("Se ha detenido la captura.");
                }
                catch
                {
                    //SetPrompt("Can't terminate capture!");
                    //SetPrompt("No se puede detener el dispositivo.");
                }
            }
        }

        #region Form Event Handlers:

        #endregion

        #region EventHandler Members:

        public void OnComplete(object Capture, string ReaderSerialNumber, DPFP.Sample Sample)
        {
            //MakeReport("The fingerprint sample was captured.");
            //SetPrompt("Scan the same fingerprint again.");
            //MakeReport("La huella digital ha sido capturada.");
            //SetPrompt("Por favor escanee el mismo dedo de nuevo.");
            Process(Sample);
        }

        public void OnFingerGone(object Capture, string ReaderSerialNumber)
        {
            //MakeReport("The finger was removed from the fingerprint reader.");
            //MakeReport("El dedo se ha quitado del lector.");
        }

        public void OnFingerTouch(object Capture, string ReaderSerialNumber)
        {
            //MakeReport("The fingerprint reader was touched.");
            //MakeReport("El dedo se ha colocado sobre el Lector.");
        }

        public void OnReaderConnect(object Capture, string ReaderSerialNumber)
        {
            //MakeReport("The fingerprint reader was connected.");
            //MakeReport("El Lector ha sido conectado.");
        }

        public void OnReaderDisconnect(object Capture, string ReaderSerialNumber)
        {
            //MakeReport("The fingerprint reader was disconnected.");
            //MakeReport("El Lector se ha desconectado.");
        }

        public void OnSampleQuality(object Capture, string ReaderSerialNumber, DPFP.Capture.CaptureFeedback CaptureFeedback)
        {
            //if (CaptureFeedback == DPFP.Capture.CaptureFeedback.Good)
                //MakeReport("The quality of the fingerprint sample is good.");
                //MakeReport("La calidad de la huella digital es buena.");
            //else
                //MakeReport("The quality of the fingerprint sample is poor.");
                //MakeReport("La calidad de la huella digital es baja.");
        }
        #endregion

        protected Bitmap ConvertSampleToBitmap(DPFP.Sample Sample)
        {
            DPFP.Capture.SampleConversion Convertor = new DPFP.Capture.SampleConversion();	// Create a sample convertor.
            Bitmap bitmap = null;												            // TODO: the size doesn't matter
            Convertor.ConvertToPicture(Sample, ref bitmap);									// TODO: return bitmap as a result
            return bitmap;
        }

        protected DPFP.FeatureSet ExtractFeatures(DPFP.Sample Sample, DPFP.Processing.DataPurpose Purpose)
        {
            DPFP.Processing.FeatureExtraction Extractor = new DPFP.Processing.FeatureExtraction();	// Create a feature extractor
            DPFP.Capture.CaptureFeedback feedback = DPFP.Capture.CaptureFeedback.None;
            DPFP.FeatureSet features = new DPFP.FeatureSet();
            Extractor.CreateFeatureSet(Sample, Purpose, ref feedback, ref features);			// TODO: return features as a result?
            if (feedback == DPFP.Capture.CaptureFeedback.Good)
                return features;
            else
                return null;
        }

        protected void SetStatus(string status)
        {
            //this.Invoke(new Function(delegate()
            //{
            //    //StatusLine.Text = status;
            //}));
        }

        protected void SetPrompt(string prompt)
        {
            //this.Invoke(new Function(delegate()
            //{
            //    //txtEstadoPrompt.Text = prompt; // Para ver el estado del dispositivo
            //}));
        }
        protected void MakeReport(string message)
        {
            //this.Invoke(new Function(delegate()
            //{
            //   // StatusText.AppendText(message + "\r\n"); // para ver los mensajes de los eventos
            //}));
        }

        private void DrawPicture(Bitmap bitmap)
        {
            //this.Invoke(new Function(delegate()
            //{                
                pictureBox1.Image = new Bitmap(bitmap, pictureBox1.Size);	// fit the image into the picture box
            //}));
        }


        private void OnTemplate(DPFP.Template template)
        {
                Template = template;
                //if (Template != null)
                //    MessageBox.Show("The fingerprint template is ready for fingerprint verification.", "Fingerprint Enrollment");
                //else
                //    MessageBox.Show("The fingerprint template is not valid. Repeat fingerprint enrollment.", "Fingerprint Enrollment");
        }



        #endregion


        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (File.Exists(@"c:\SFSPOS\BIO\LC-FINGER\Template.fpt"))
            {
                File.Delete(@"c:\SFSPOS\BIO\LC-FINGER\Template.fpt");
            }

            if (MessageBox.Show("Desea salir realmente?", "Confirm guardar", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Stop();
                this.Close();
                this.Dispose();
            }

            
        }

    
        private void AltaUsuario_Load(object sender, EventArgs e)
        {
            string IdEmpresa = Settings1.Default.IdEmpresa;
            string IdSucursal = Settings1.Default.IdSucursal;

            cmbEmpleados.DataSource = null;
            cmbEmpleados.Items.Clear();

            ConectaBD conBD = new ConectaBD();
            DataSet ds = conBD.Consulta("Select IdEmpleado, Nombre from reloj_empleados Where IdEmpresa = " + IdEmpresa + " And IdSucursal = '" + IdSucursal + "' and idEmpleado='" + this.Id_empleado + "'");

            if (ds.Tables.Count == 0 )
            {
                MessageBox.Show("Error en la consulta de empleados (T)", "Alta de usuarios", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }


            if (ds.Tables["Resultado"].Rows.Count == 0)
            {
                MessageBox.Show("Error en la consulta de empleados (R)", "Alta de usuarios", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            ArrayList arreglo = new ArrayList();
            foreach (DataRow dr2 in ds.Tables["Resultado"].Rows)
            {
                arreglo.Add(new ConectaBD.clsEmpleados(dr2["Nombre"].ToString(), dr2["IdEmpleado"].ToString()));                
            }
            label3.Text = conBD.conexioStatus;
            cmbEmpleados.DataSource = arreglo;
            cmbEmpleados.DisplayMember = "NombreEmpleado";
            cmbEmpleados.ValueMember = "IdEmpleado";
            cmbEmpleados_SelectedIndexChanged(cmbEmpleados, System.EventArgs.Empty);

            // Inicializar el lector 
            Init();
            Start();

        }

        

        private void cmbEmpleados_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

       
       

        private void button4_Click_1(object sender, EventArgs e)
        {
            ImagenTemplate = null;
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Fingerprint Template File (*.fpt)|*.fpt";
            if (open.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fs = File.OpenRead(open.FileName))
                {

                    DPFP.Template template = new DPFP.Template(fs);
                    ImagenTemplate = template;
                    //OnTemplate(template);
                }
            }

        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            // Guardar en un archivo Temporal para su posterior validacion
            string Directorio = @"c:\SFSPOS\BIO\LC-FINGER\";
            if (!Directory.Exists(Directorio))
            {
                Directory.CreateDirectory(Directorio);
            }
            string NombreArchivo = @"c:\SFSPOS\BIO\LC-FINGER\Template.fpt";
            if (File.Exists(NombreArchivo))
            {
                File.Delete(NombreArchivo);
            }
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Fingerprint Template File (*.fpt)|*.fpt";
            save.FileName = NombreArchivo;
            using (FileStream fs = File.Open(save.FileName, FileMode.Create, FileAccess.Write))
            {
                Template.Serialize(fs);
            }
            ///////////////////////////////////////////////////////////

        }

        private void btnCreaTemporal_Click(object sender, EventArgs e)
        {
            btnCreaTemporal.Enabled = false;

            if (Template == null)
            {
                MessageBox.Show("Imagen no válida para crear Temporal", "Administración de Huella", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            ///////////////////////////////////////////////////////////
            // Guardar en un archivo Temporal para su posterior validacion
            string Directorio = @"c:\SFSPOS\BIO\LC-FINGER\";
            if (!Directory.Exists(Directorio))
            {
                Directory.CreateDirectory(Directorio);
            }
            
            string NombreArchivo = @"c:\SFSPOS\BIO\LC-FINGER\Template.fpt";
            if (File.Exists(NombreArchivo))
            {
                File.Delete(NombreArchivo);
            }
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Fingerprint Template File (*.fpt)|*.fpt";
            save.FileName = NombreArchivo;
            using (FileStream fs = File.Open(save.FileName, FileMode.Create, FileAccess.Write))
            {                
                    Template.Serialize(fs);
            }
            ///////////////////////////////////////////////////////////


            ///////////////////////////////////////////////////////////
            // Leer el Archivo Temporal Guardado para poder validar
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "Fingerprint Template File (*.fpt)|*.fpt";
            open.FileName = NombreArchivo;
            using (FileStream fs2 = File.OpenRead(open.FileName))
            {
                Bitmap tmpBitmap;
                tmpBitmap = ConvertSampleToBitmap(ImagenSample);
                pictureBox2.Image = new Bitmap(tmpBitmap, pictureBox2.Size);

                // Crea el objeto Template para la validacion
                DPFP.Template template = new DPFP.Template(fs2);
                ImagenTemplate = template; // ImagenTemplate se va a usar para validar la huella temporal con la nueva huella que ingresen para validar.
            }
            ///////////////////////////////////////////////////////////

            lblMensaje.Text = "Imagen lista para validar ...";
            lblMensaje.Visible = true;
            lblEstatus.Visible = true;
            btnValidarHuella.Enabled = true;
           /// btnCreaTemporal.Enabled = true;
            //MessageBox.Show("Imagen actualizada", "Administracion de Huella", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void btnValidarHuella_Click(object sender, EventArgs e)
        {
            lblEstatus.Text = "Estatus: ";
             
            Verificator = new DPFP.Verification.Verification();		// Create a fingerprint template verificator

            // Process the sample and create a feature set for the enrollment purpose.
            DPFP.FeatureSet features = ExtractFeatures(ImagenSample, DPFP.Processing.DataPurpose.Verification);

            // Check quality of the sample and start verification if it's good
            if (features != null)
            {

                // Compare the feature set with our template
                DPFP.Verification.Verification.Result result = new DPFP.Verification.Verification.Result();
                Verificator.Verify(features, ImagenTemplate, ref result);

                lblEstatus.Text = "Estatus: OK";
                //UpdateStatus(result.FARAchieved);
                if (result.Verified)
                {
                    //MakeReport("The fingerprint was VERIFIED.");
                    btnGuardar.Enabled = true;
                    lblEstatus.Text = "Estatus: Imagen VALIDA !!!";
                    lblEstatus.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    btnGuardar.Enabled = false;
                    //MakeReport("The fingerprint was NOT VERIFIED.");
                    lblEstatus.Text = "Estatus: Imagen No Valida.";
                    lblEstatus.ForeColor = System.Drawing.Color.Red;
                }
                //}

            }

        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            IdEmpleado = Convert.ToString(cmbEmpleados.SelectedValue);
                string Directorio = @"c:\SFSPOS\BIO\LC-FINGER\";
                if (!Directory.Exists(Directorio))
                {
                    Directory.CreateDirectory(Directorio);
                }

                string NombreArchivo = @"c:\SFSPOS\BIO\LC-FINGER\" + IdEmpleado + ".fpt";

                if (File.Exists(NombreArchivo))
                {
                    File.Delete(NombreArchivo);
                }

                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "Fingerprint Template File (*.fpt)|*.fpt";
                save.FileName = NombreArchivo;
                using (FileStream fs = File.Open(save.FileName, FileMode.Create, FileAccess.Write))
                {
                    ImagenTemplate.Serialize(fs);
                }

                if (File.Exists(@"c:\SFSPOS\BIO\LC-FINGER\Template.fpt"))
                {
                    File.Delete(@"c:\SFSPOS\BIO\LC-FINGER\Template.fpt");
                }

                ReseteaObjetos();

                MessageBox.Show("Imagen actualizada", "Administración de Huella", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            ReseteaObjetos();
        }

        private void ReseteaObjetos()
        {
            lblEstatus.Text = "Estatus:";
            lblEstatus.ForeColor = System.Drawing.Color.Blue;
            lblMensaje.Text = "";
            btnValidarHuella.Enabled = false;
            btnGuardar.Enabled = false;
            Template = null;
            ImagenSample = null;
            ImagenSampleValidar = null;
            ImagenTemplate = null;
            pictureBox1.Image = null;
            pictureBox2.Image = null;
            Stop();
            Init();
            Start();
            btnCreaTemporal.Enabled = true;
        }

        private void rbhuella_CheckedChanged(object sender, EventArgs e)
        {
            ReseteaObjetos();
            btnGuardar.Enabled = false;
        }

        public void sendUserSelected(string idUsuario)
        {
            Id_empleado = idUsuario;
        }

    }
}
